package com.mydemo.controller;

import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.annotation.Resource;
import org.springframework.ai.image.ImageModel;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Text2ImgController {


    public static final String IMAGE_MODEL="wanx2.1-t2i-turbo";

    @Resource
    private ImageModel imageModel;

    @GetMapping("/text2img")
    public String text2Img(@RequestParam(name = "prompt",defaultValue = "刺猬") String prompt){

        return imageModel.call(new ImagePrompt(
                        prompt, DashScopeImageOptions
                .builder()
                .withModel(IMAGE_MODEL).build())
                )
                .getResult()
                .getOutput()
                .getUrl();
    }

    //上面的简单代码存在问题
    //java.lang.RuntimeException: Image generation still pending 异常表明图像生成请求已发送，但图像尚未生成完成，而代码尝试立即获取图像URL。
    //解决办法 增加重试机制和等待逻辑
    @GetMapping("/text2img2")
    public String text2Img2(@RequestParam(name = "prompt", defaultValue = "刺猬") String prompt) {
        int maxRetries = 10;
        int retryInterval = 2000; // 2秒

        for (int i = 0; i < maxRetries; i++) {
            try {
                ImageResponse response = imageModel.call(new ImagePrompt(
                        prompt, DashScopeImageOptions
                        .builder()
                        .withModel(IMAGE_MODEL)
                        .build()));

                String url = response.getResult().getOutput().getUrl();
                if (url != null && !url.isEmpty()) {
                    return url;
                }
            } catch (RuntimeException e) {
                if (e.getMessage().contains("Image generation still pending")) {
                    try {
                        Thread.sleep(retryInterval);
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        throw new RuntimeException("Interrupted while waiting for image generation", ie);
                    }
                    continue;
                }
                throw e;
            }
        }

        throw new RuntimeException("Image generation timeout after " + maxRetries + " attempts");
    }



}
